package com.example.woh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.woh.entity.BO.PicUrl;
import com.example.woh.entity.Homework;
import com.example.woh.entity.Submit;
import com.example.woh.entity.VO.HomeworkVO1;
import com.example.woh.entity.VO.HomeworkVO2;
import com.example.woh.exception.ArgumentException;
import com.example.woh.service.IHomeworkService;
import com.example.woh.service.IQuestionService;
import com.example.woh.service.ISubmitService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

import static com.example.woh.mapper.GlobalConstance.IMAGE_ROOT_URL;
import static com.example.woh.mapper.GlobalConstance.IMAGE_UPLOAD_URL;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sail
 * @since 2023-03-24
 */
@RestController
@RequestMapping("/submit")
@RequiredArgsConstructor
public class SubmitController {
    private final IHomeworkService homeworkService;
    private final IQuestionService questionService;
    private final ISubmitService submitService;
    private final RestTemplate restTemplate;

    @GetMapping("/getUnfinished")
    public ResponseEntity<List<Homework>> getUnfinished(Integer userId){
        List<Homework> homeworkList = submitService.getUnfinishedList(userId);
        for (Homework h : homeworkList) {
            h.setQuestionList(questionService.queryByHomeworkId(h.getId()));
        }
        return ResponseEntity.ok(homeworkList);
    }

    @GetMapping("/getFinished")
    public ResponseEntity<List<HomeworkVO2>> getFinished(Integer userId){
        List<Homework> homeworkList = submitService.getFinishedList(userId);
        List<HomeworkVO2> homeworkVO2List = new ArrayList<>();
        for (Homework h : homeworkList) {
            h.setQuestionList(questionService.queryByHomeworkId(h.getId()));
            HomeworkVO2 homeworkVO2 = new HomeworkVO2();


            QueryWrapper<Submit> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("homework_id",h.getId()).eq("user_id",userId);
            Submit submit = submitService.getOne(queryWrapper);

            BeanUtils.copyProperties(h, homeworkVO2);
            homeworkVO2.setScore(submit.getScore());
            homeworkVO2.setAnswer(submit.getAnswer());
            homeworkVO2.setSrc(submit.getSrc());
            homeworkVO2.setSubmitTime(submit.getTime());
            homeworkVO2List.add(homeworkVO2);
        }
        return ResponseEntity.ok(homeworkVO2List);
    }

    @GetMapping("/getUnsubmit")
    public ResponseEntity<List<HomeworkVO1>> getUnsubmit(Integer publishId){
        return ResponseEntity.ok(getHomeworkVO1(publishId,-2));
    }
    @GetMapping("/getSubmit")
    public ResponseEntity<List<HomeworkVO1>> getSubmit(Integer publishId){
        return ResponseEntity.ok(getHomeworkVO1(publishId,-1));
    }


    /**
     * 提交作业
     * @param answer 文字答案
     * @param file 图片答案
     */
    @PostMapping("/submitHomework")
    public ResponseEntity<String> submitHomework(Integer homeworkId,Integer userId,
                                                 @RequestParam(required = false) String answer,
                                                 @RequestParam(required = false) MultipartFile file) {
        QueryWrapper<Submit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("homework_id",homeworkId).eq("user_id",userId);
        Submit submit = submitService.getOne(queryWrapper);
        if (answer != null){
            submit.setAnswer(answer);
        }
        submit.setScore(-1);

        if (file!=null){
//            String avatarUrl = submitService.upload(file);
            MultiValueMap<String,Object> param = new LinkedMultiValueMap<>();

            HttpHeaders headers = new HttpHeaders();
            headers.add("user-agent", "1");
            HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(param, headers);

            param.add("file", file.getResource());
            PicUrl[] res = restTemplate.postForObject(IMAGE_UPLOAD_URL, files, PicUrl[].class);
            String src=IMAGE_ROOT_URL + res[0].getSrc().replace("\\", "").substring(1);
            if (!StringUtils.hasLength(src)) {
                throw new RuntimeException("用户头像上传失败");
            }
            submit.setSrc(src);
        }

        boolean update = submitService.update(submit, queryWrapper);
        if (update){
            return ResponseEntity.ok("提交成功");
        }
        throw new ArgumentException("更新失败");

    }

    @PostMapping("/submitScore")
    public  ResponseEntity<String> submitScore(Integer score,Integer id){
        Submit submit = submitService.getById(id);
        submit.setScore(score);
        if (submitService.updateById(submit)){
            return ResponseEntity.ok("成功");
        }
        throw new ArgumentException("更新失败");

    }

    private List<HomeworkVO1> getHomeworkVO1(Integer publishId,Integer score){
        QueryWrapper<Homework> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("publish_id",publishId);
        List<Homework> homeworkList = homeworkService.list(queryWrapper);
        List<HomeworkVO1> homeworkVO1List = new ArrayList<>();

        for (Homework h : homeworkList) {
            h.setQuestionList(questionService.queryByHomeworkId(h.getId()));

            QueryWrapper<Submit> submitQueryWrapper = new QueryWrapper<>();
            if (score==-2){
                submitQueryWrapper.eq("homework_id",h.getId()).eq("score",-2);
            }else {
                submitQueryWrapper.eq("homework_id",h.getId()).ge("score",-1);
            }

            List<Submit> submitList = submitService.list(submitQueryWrapper);
            if (submitList!=null && !submitList.isEmpty()){
                HomeworkVO1 homeworkVO1 = new HomeworkVO1();
                BeanUtils.copyProperties(h,homeworkVO1);
                homeworkVO1.setSubmitList(submitList);
                homeworkVO1List.add(homeworkVO1);
            }

        }
        return homeworkVO1List;
    }


}
